<!-- 健康档案管理-表类目管理 -->
<template>
  <div class="chart-category pad">
    <div class="head">
      <span>表类目管理</span>
      <el-button
        type="primary"
        circle
        icon="el-icon-plus"
        @click="openAddCategoryDialog"
      ></el-button>
    </div>
    <el-table :data="categoryList" stripe border class="m-t-b" v-loading="isLoading">
      <el-table-column label="分类名称" prop="categoryTitle"></el-table-column>
      <el-table-column label="分类排序" prop="categorySort"></el-table-column>
      <el-table-column label="分类图标">
        <template slot-scope="scope">
          <img
            v-if="scope.row.categoryIcon"
            :src="scope.row.categoryIcon"
            style="width: 40px; height: 40px;"
          />
          <span v-else>暂无图标</span>
        </template>
      </el-table-column>
      <el-table-column label="分类描述">
        <template slot-scope="scope">
          {{scope.row.categoryDescribe || '暂无描述'}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createDate"></el-table-column>
      <el-table-column label="启用/禁用">
        <template slot-scope="scope">
          <el-switch
            active-text="启用"
            inactive-text="禁用"
            v-model="scope.row.enable"
            @change="changeCategoryStatus($event, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="default" circle icon="el-icon-edit" @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" circle icon="el-icon-delete" @click="fetchDeleteCategory(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="categoryDialogTitle" :visible.sync="showCategoryDialog">
      <el-form :model="category" ref="category" :rules="rules" label-position="top">
        <el-form-item label="分类名称" prop="chartCategoryTitle">
          <el-input v-model="category.chartCategoryTitle" />
        </el-form-item>
        <el-form-item label="分类排序" prop="chartCategorySort">
          <el-input type="number" v-model="category.chartCategorySort" min="1" />
        </el-form-item>
        <el-form-item label="分类图标" prop="chartCategoryIcon" ref="chartsIcon">
          <img
            :src="category.chartCategoryIcon"
            v-if="category.chartCategoryIcon"
            style="width: 60px; height: 60px;"
          />
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :http-request="uploadIcon"
            :show-file-list	="false"
          >
            <el-button size="small" type="primary" :loading="isUploading" >点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类描述" prop="chartCategoryDescribe">
          <el-input type="textarea" rows="8" v-model="category.chartCategoryDescribe" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideCategoryDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddCategory('category')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { fileToBase64, formatDate } from '../util/index';
import {
  uploadImage,
  getAllCategory,
  addCategory,
  updateCategory,
  deleteCategory
} from '../api';
import {
  updateChartCategoryStatus
} from '../api/version2';

export default {
  name: 'ChartCategory',
  data () {
    return {
      // chartCategorySort:'1',
      uploadUrl: '',
      showCategoryDialog: false,
      isLoading: false,
      categoryDialogTitle: '添加类目',
      isUploading: false,
      isDoing: false,
      category: { // 分类
        chartCategoryTitle: '',
        chartCategorySort: '',
        chartCategoryIcon: '',
        chartCategoryDescribe: ''
      },
      categoryList: [],
      rules: {
        chartCategoryTitle: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        chartCategorySort: [
          { required: true, message: '分类排序不能为空', trigger: 'blur' }
        ],
        chartCategoryIcon: [
          { required: true, message: '请上传分类图标', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openAddCategoryDialog () { // 打开添加类目弹出框
      if (!this.$checkAuth('canAddChartCategory')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.category.chartCategoryTitle = '';
      this.category.chartCategorySort = '1';
      this.category.chartCategoryIcon = '';
      this.category.chartCategoryDescribe = '';
      this.categoryDialogTitle = '添加类目';
      this.showCategoryDialog = true
    },
    hideCategoryDialog () { // 隐藏类目弹出框
      this.showCategoryDialog = false
    },
    changeCategoryStatus (e, row) { // 切换分类状态
      this.$confirm(`确定 ${e ? '启用' : '禁用'} 分类${row.categoryTitle}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        updateChartCategoryStatus(row.categoryId, Number(e))
        .then(res => {
          this.$message.success('操作成功!');
          this.fetchCategory()
        })
        .catch(e => {

        })
      })
      .catch(err => {
        row.enable = !e
      })
    },
    uploadIcon ({ file }) { // 上传s表icon图标
      this.isUploading = true;
      fileToBase64(file, (base64) => {
        uploadImage(base64)
        .then(res => {
          if (res.data.code === 1) {
            let { path } = res.data.data;
            let pathArr = path.split(':');
            this.category.chartCategoryIcon = `${pathArr[0]}s:${pathArr[1]}`
            if(this.$refs.chartsIcon != null){
              this.$refs.chartsIcon.clearValidate()
            }
          } else {
            this.$message.error(res.data.msg || '上传失败!')
          };
          this.isUploading = false
        })
        .catch(e => {
          this.isUploading = false;
          this.$message.error('上传失败!')
        })
      })
    },
    fetchAddCategory (name) { // 添加分类
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          if (this.categoryDialogTitle === '添加类目') {
            addCategory({
              categoryTitle: this.category.chartCategoryTitle,
              categorySort: this.category.chartCategorySort,
              categoryIcon: this.category.chartCategoryIcon,
              categoryDescribe: this.category.chartCategoryDescribe || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                // 这里应该进行根据分类排序的id值进行从大到小排序
                this.showCategoryDialog = false;
                this.fetchCategory()
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          } else {
            console.log('更新类目', this.category.chartCategoryIcon);
            updateCategory({
              categoryId: this.category.categoryId,
              categoryTitle: this.category.chartCategoryTitle,
              categorySort: this.category.chartCategorySort,
              categoryIcon: this.category.chartCategoryIcon,
              categoryDescribe: this.category.chartCategoryDescribe || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showCategoryDialog = false;
                this.fetchCategory()
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchCategory () { // 获取分类列表
      this.isLoading = true;
      getAllCategory()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          list.forEach(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            item.enable = Boolean(item.categoryEnable)
          });
          this.categoryList = list;
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.isLoading = false
      })
      .catch(e => {
        this.isLoading = false;
        this.$message.error('服务异常!')
      })
    },
    openEditDialog (data) { // 打开修改弹出框
      if (!this.$checkAuth('canEditChartCategory')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.category.chartCategoryTitle = data.categoryTitle;
      this.category.chartCategorySort = data.categorySort;
      this.category.chartCategoryIcon = data.categoryIcon;
      this.category.chartCategoryDescribe = data.categoryDescribe;
      this.category.categoryId = data.categoryId;
      this.categoryDialogTitle = '修改类目';
      this.showCategoryDialog = true
    },
    fetchDeleteCategory (data) { // 删除类目
      if (!this.$checkAuth('canDeleteChartCategory')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm(`确定删除分类: ${data.chartCategoryTitle}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteCategory(data.chartCategoryId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchCategory()
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    }
  },
  created () {
    this.uploadUrl = this.$uploadUrl;
    this.fetchCategory()
  }
}
</script>
<style lang="scss">
  .chart-category {

  }
</style>
